import pyqtgraph as pg
import threading
import numpy as np

from pyqtgraph.Qt import QtCore
import sys



from PyQt5.QtWidgets import QApplication



class CurvePlotter(object):
    # global curves
    """docstring for CurvePlotter"""
    def __init__(self,  *args, **kwargs):
        super(CurvePlotter, self).__init__()
        self.args = args
        self.kwargs = kwargs

        self.pw = self.kwargs["pw"]


        self.curve_data_max_len = 2000
        self.scale_offset = 200

        self.ch_list = ['TP9','C4','C3','F4',   'F3','Fp2','Fp1','Fz']
        self.CH_NUM = len(self.ch_list)
        color_list = [(255,0,0),(0,255,0),(0,0,255),(0,255,255),(255,0,255),(255,255,0),(128,128,0),(128,0,128)]


        self.curves=[]
        for i,ch in enumerate(self.ch_list):
            c = self.pw.plot(pen=color_list[i])
            self.curves.append(c) 

        self.data = np.empty(shape=(0,self.CH_NUM))
        self.x = np.empty(shape=(0))
        self.ind_x_last = 0

        self.fs = kwargs.get("fs", None)
        self.fs = float(self.fs)

    def display_args(self):
        # 输出接收到的参数
        print("Position arguments:", self.args)
        print("Keyword arguments:", self.kwargs)

    def new_data(self,arr):


        tmp = np.arange(0, arr.shape[0]) 
        ind_x = self.ind_x_last + tmp
        self.ind_x_last = ind_x[-1]+1
        # print(self.ind_x_last)

        self.x = np.concatenate((self.x,ind_x), axis=0)
        self.data = np.concatenate((self.data,arr), axis=0)

        num_del = self.data.shape[0] - self.curve_data_max_len
        if(num_del>0):
            self.data = np.delete(self.data,np.s_[:num_del], axis=0)
            self.x = np.delete(self.x,np.s_[:num_del], axis=0)

        if self.fs is not None:
            x = self.x/self.fs
        else:
            x = self.x

        # print(x)

        # show_ch = [0,1,2,3,4,5,6,7]
        show_ch = [3]
        for ch in show_ch:
            # curves[ch].setData(y=self.data[:, ch]+self.scale_offset*ch)
            self.curves[ch].setData(x=x, y=self.data[:, ch]+self.scale_offset*ch)


if __name__ == '__main__':


    app = pg.mkQApp("Plotting Example")
#mw = QtWidgets.QMainWindow()
#mw.resize(800,800)

    win = pg.GraphicsLayoutWidget(show=True, title="Basic plotting examples")
    pw = win.addPlot(title="Sig")

    pw.setLabel('bottom', 'Time', 's')

    obj = CurvePlotter(pw = pw, fs=500)
    obj.display_args()

    SN_PKG = 10
    CH_NUM = 8

    def update():
        global obj
        random_matrix = np.random.rand(SN_PKG, CH_NUM)
        obj.new_data(random_matrix)

    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(100)

    pg.exec()